// import Nevow.Athena
// import Divmod.Runtime

Meercat.Form = Nevow.Athena.Widget.subclass('Meercat.Form');
Meercat.SubForm = Meercat.Form.subclass('Meercat.SubForm');

Meercat.Form.methods(
function submit(self) {
    var data = new Object();
    
    jQuery('#' + escapeId(self.node.id) + ' :input').each(function (input) {
        var input = jQuery(this);
    
        if (input.attr('name')) {
            data[input.attr('name')] = input.val();
        }
    });
    
    var d = self.callRemoteKw('submit', data);
    self.addSubmitCallbacks(d);
    self.addSubmitErrbacks(d);
},
function addSubmitCallbacks(self, deferred) {
    deferred.addCallback(function (result) {
        self.remove();
    });
},
function addSubmitErrbacks(self, deferred) {
    deferred.addErrback(function (failure) {
        alert('Error submitting the form: ' + failure);
    });
},
function remove(self) {
    var d = self.detach();
    d.addCallback(function (result) {
        jQuery('#' + escapeId(self.node.id)).remove();
    });
    
    d.addErrback(function (failure) {
        alert('Error detaching the form: ' + failure);
    });
});

Meercat.SubForm.methods(
function addSubmitCallbacks(self, deferred) {
    deferred.addCallback(function (result) {
        self.widgetParent.widgetParent.refresh();
        self.widgetParent.remove();
    });
});